<?php
App::import('Sanitize');

class JobsController extends AppController {
	var $helpers = array ('Html','Form', 'Javascript', 'Ajax');
	var $name = 'Jobs';

	function index() {
		$this->set('jobs', $this->Job->find('all'));
	}
    
    function view($id = null) {
		$this->Job->id = $id;
		$this->set('job', $this->Job->read());
	}
    function jadd()
    {
        
         if(!empty($this->data)) 
         {
            $starttime = $this->data['Job']['stime'];
            $this->data['Job']['sdate'] = $this->data['Job']['sdate']. ' ' . $this->data['Job']['stime']. ':00';
            $startdate = $this->data['Job']['sdate'];
            $startdate = date_parse($startdate);
            
            $endtime = $this->data['Job']['etime'];
            
            $enddate = date("Y-m-d H:i:s", mktime(($startdate['hour']+$endtime), $startdate['minute'], $startdate['second'], $startdate['month'], $startdate['day'], $startdate['year']));
            $this->data['Job']['edate'] = $enddate;
            
            unset($this->data['Job']['stime']);
            unset($this->data['Job']['etime']);
            //$this->set('output', $this->data);
            if($this->Job->save($this->data))
                {
                    //$this->Session->setFlash("Job Saved!");
                    $this->redirect('/jobs/jview');
                }
         }
        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
    }


    function jaddOLD()
    {

         if(!empty($this->data))
         {
            $this->data['Job']['sdate'] = $this->data['Job']['sdate']. ' ' . $this->data['Job']['stime']. ':00';

            $this->data['Job']['edate'] = $this->data['Job']['edate']. ' ' . ($this->data['Job']['stime'] + $this->data['Job']['etime']);

            unset($this->data['Job']['stime']);
            unset($this->data['Job']['etime']);
            //$this->set('output', $this->data);
            if($this->Job->save($this->data))
                {
                    //$this->Session->setFlash("Job Saved!");
                    $this->redirect('/jobs/jview');
                }
         }
        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
    }

    function jdelete($id)
    {
        $this->autoRender = false;
        $this->Job->delete($id);
        $this->Session->setFlash('The task has been deleted.');
        $this->redirect(array('action'=>'jadminlist'));
    }

    function jedit($id)
    {
        if(isset($this->data))
        {
            $this->data['Job']['id'] = $id;
            $this->Job->id = $id;
            $this->data['Job']['sdate'] = $this->data['Job']['sdate']. ' ' . $this->data['Job']['stime']. ':00';
            $this->data['Job']['edate'] = $this->data['Job']['sdate'];
            $this->Job->save($this->data);
            //echo pr($this->data);
            $this->Session->setFlash('The task has been edited.');
            $this->redirect('/jobs/jadminlist');
        }
        $this->set('jb', $this->Job->findallByid($id));
        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
    }


    function jeditOLD($id)
    {
        if(isset($this->data))
        {
            $this->data['Job']['id'] = $id;
            $this->Job->id = $id;
            $this->data['Job']['sdate'] = $this->data['Job']['sdate']. ' ' . $this->data['Job']['stime']. ':00';
            $this->data['Job']['edate'] = $this->data['Job']['edate']. ' ' . ($this->data['Job']['stime'] + $this->data['Job']['etime']);
            $this->Job->save($this->data);
            //echo pr($this->data);
            $this->Session->setFlash('The task has been edited.');
            $this->redirect('/jobs/jadminlist');
        }
        $this->set('jb', $this->Job->findallByid($id));
        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
    }

    function jview()
    {
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard      
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job Order By Job.created desc LIMIT 10'));
        //Below will create a full event list that will create the events array for the calendar. 
        $this->set('felist', $this->Job->find('all'));
        //echo $this->Auth->user('active');
    }

    function jlistviewz()
    {
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job Order By Job.created desc LIMIT 10'));
        //Below will create a full event list that will create the events array for the calendar.
        $this->set('felist', $this->Job->find('all'));

    }
    
    function jlistview($view = null)
    {
        $farback = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")-10, date("Y")));
        if ($view == 'mine') {
            $this->set('felist', $this->Job->User->findByid($this->Auth->user('id')));
        }
        else{
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.sdate > \''.$farback.'\' Order By Job.sdate asc'));
        //Below will create a full event list that will create the events array for the calendar.
        //$this->set('felist', $this->Job->find('all'));
            }
    }
    
    function jadminlist($view = null)
    {
        $today = date('Y-m-d H:i:s');
        $tenago = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m"), date("d")-10, date("Y")));
        $monthago = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m")-1, date("d"), date("Y")));
       switch ($view)
       {
       case null:
            $this->set('felist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.sdate > \''.$today.'\' Order By Job.sdate desc'));
            $this->set('filterview', 'Upcoming Tasks');
            break;
       case '10days':
            $this->set('felist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.sdate BETWEEN \''.$tenago.'\' AND \''.$today.'\' ORDER BY Job.sdate desc'));
            $this->set('filterview', '10 Days Ago');
            break;
       case '1month':
            $this->set('felist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.sdate BETWEEN \''.$monthago.'\' AND \''.$today.'\' ORDER BY Job.sdate desc'));
            $this->set('filterview', '1 Month Ago');
            break;
       }
    }
    
    function jadminnonvol($view = null)
    {
        if ($view == 'mine') {
            $this->set('felist', $this->Job->User->findByid($this->Auth->user('id')));
        }
        else{
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.hasvolunteer = 0 Order By Job.sdate desc LIMIT 10'));
        //Below will create a full event list that will create the events array for the calendar.
        $this->set('felist', $this->Job->query('SELECT * FROM jobs as Job WHERE Job.hasvolunteer = 0 Order By Job.sdate asc'));
            }
    }
    
    function mytasks($view = null)
    {
        $this->User->recursive=-1;
         $options['joins'] = array(
                    array('table' => 'jobs_users',
                        'alias' => 'JobsUser',
                        'type' => 'inner',
                        'conditions' => array(
                            'Job.id = JobsUser.job_id'
                                            )
                    ),
                    array('table' => 'users',
                        'alias' => 'User',
                        'type' => 'inner',
                        'conditions' => array(
                            'JobsUser.user_id = User.id'
                                            )
                        )
            );
        $options['conditions'] = array(array(
                'User.id' => $this->Auth->user('id'), 'Job.sdate >' => date('Y-m-d H:i')
                ));
        $options['order'] = array(array('Job.sdate DESC'));
            $this->set('felist', $this->Job->find('all', $options));
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job Order By Job.created desc LIMIT 10'));
        //Below will create a full event list that will create the events array for the calendar.
        //$this->set('felist', $this->Job->find('all'));
            
    }

function prevtasks($view = null)
    {
        $this->User->recursive=-1;
         $options['joins'] = array(
                    array('table' => 'jobs_users',
                        'alias' => 'JobsUser',
                        'type' => 'inner',
                        'conditions' => array(
                            'Job.id = JobsUser.job_id'
                                            )
                    ),
                    array('table' => 'users',
                        'alias' => 'User',
                        'type' => 'inner',
                        'conditions' => array(
                            'JobsUser.user_id = User.id'
                                            )
                        )
            );
        $options['conditions'] = array(array(
                'Job.sdate <' => date('Y-m-d H:i'), 'User.id' => $this->Auth->user('id')
                ));
            $this->set('felist', $this->Job->find('all', $options));
        
        
        //Below will create a 10 most recent list to be used by the recent task part of the dashboard
        $this->set('tlist', $this->Job->query('SELECT * FROM jobs as Job Order By Job.created desc LIMIT 10'));
        //Below will create a full event list that will create the events array for the calendar.
        //$this->set('felist', $this->Job->find('all'));
            
    }

    function jdetail($id)
    {
        $thistask = $this->Job->findallByid($id);
        $this->set('jdetail', $thistask);
        $this->set('uid', $this->Auth->user('id'));
        
        // mixing it up!!!
            $i = 1;
            
            $skchecked = '\'\'';
            if(!empty($thistask[0]['Skill']))
            {
            foreach($thistask[0]['Skill'] as $sk)
            {
                if ($i == 1)
                {
                    $skchecked = '\'' . $sk['id'] . '\'';
                }
                else
                {
                    $skchecked = $skchecked . ', ' . '\'' . $sk['id'] . '\'';
                }
                $i++;
                
            }
            }
            //$this->set('output', $skchecked);
           
       $findings = $this->Job->query('Select * from users as User where User.id = \''. $this->Auth->user('id') . '\' AND not exists (select * from skills as skill where skill.id in ('. $skchecked . ') and not exists(select * from skills_users as su where User.id = su.user_id and su.skill_id = skill.id));');
        
        //$this->set('found', $findings);
        if(!empty($findings[0]))
        {
           // $this->set('qualified', 'You have the skills to perform this task');
            $this->set('qualified', 'Yes');
        }
        else
        {
           // $this->set('qualified', 'You are not eligable for the task');
            $this->set('qualified', 'No');
        }
        
    }
    
    function jadmindetail($id)
    {
        
        $this->set('jadmindetail', $this->Job->findallByid($id));
        $this->set('uid', $this->Auth->user('id'));
        
        App::import('Model', 'User');
        $us = new User();
        $this->set('user', $us->find('all', array('conditions' => array('User.active' => '1'))));
    }
    
    function addvol($id)
    {
        
        if (!empty($this->data))
        {
            $this->Job->id = $id;
            $this->data['Job']['hasvolunteer'] = 1;       
            $this->Job->save($this->data);
            $this->Session->setFlash('You have successfully volunteered for the task');
            $this->redirect('/jobs/mytasks');  
            //echo pr($this->data); 
        }
    }
    
    function assignvol($uid, $jid)
    {
        //echo pr($this->data);
        
        $this->Session->setFlash('You have successfully assigned the volunteer for the task');
        $this->set('usr', $uid);
        $this->set('task', $jid);
        
        $this->Job->id = $jid;
        $this->data['Job']['id'] = $jid;
        $this->data['User']['id'] = $uid;
        $this->data['Job']['hasvolunteer'] = 1;
        
        //echo pr($this->data);
        
        
        if ($this->Job->save($this->data))
        {
            $this->redirect('/jobs/jadmindetail/'.$jid);   
        }
    }
    
    function delvol($id)
    {
        //$this->autoRender = false;
        
        $this->Job->id = $id;
        $this->data['Job']['hasvolunteer'] = 0;
        $this->Job->save($this->data);
        $this->Job->JobsUser->deleteAll(array('JobsUser.user_id' => $this->Auth->user('id'), 'JobsUser.job_id' => $id));
        $this->redirect('/jobs/jlistview');
        
    }
    function unvol($jid, $uid)
    {
        //$this->autoRender = false;
        
        $this->Job->id = $jid;
        $this->data['Job']['hasvolunteer'] = 0;
        $this->Job->save($this->data);
        $this->Job->JobsUser->deleteAll(array('JobsUser.user_id' => $uid, 'JobsUser.job_id' => $jid));
        $this->Session->setFlash('User has been removed from the task');
        $this->redirect('/jobs/jadmindetail/'.$jid);
        
    }
    function fox()
    {
        
        //Below will create a full event list that will create the events array for the calendar. 
        $this->set('felist', $this->Job->find('all'));
        
    }
    function feed() {
        //1. Transform request parameters to MySQL datetime format.
        $mysqlstart = date( 'Y-m-d H:i:s', $this->params['url']['start']);
        $mysqlend = date('Y-m-d H:i:s', $this->params['url']['end']);
        
        //2. Get the events corresponding to the time range
        $conditions = array('Job.sdate BETWEEN ? AND ?' => array($mysqlstart,$mysqlend));
        $jobs = $this->Job->find('all',array('conditions' =>$conditions));
        
        //3. Create the json array
        $rows = array();
        for ($a=0; count($jobs)> $a; $a++) 
        {
            //Is it an all day event?
            $all = ($jobs[$a]['Job']['allday'] == 1);
        
            //Create an event entry
            $rows[] = array(
                'id' => $jobs[$a]['Job']['id'],
                'title' => $jobs[$a]['Job']['title'],
                'start' => date('Y-m-d H:i', strtotime($jobs[$a]['Job']['sdate'])),
                'end' => date('Y-m-d H:i',strtotime($jobs[$a]['Job']['edate'])),
                'allDay' => $all,
                'className' => 'fullevent'
                );
        }
        
        //4. Return as a json array
        //Configure::write('debug', 0);
        $this->autoRender = false;
        $this->autoLayout = false;
        $this->header('Content-Type: application/json');
        echo json_encode($rows);
    }
    function jaddnote($jid)
    {
        App::import('Model', 'User');
        $usr = new User();
        
        //$this->set('usr', $usr->findByid($this->Auth->user('id')));
        $this->set('task', $this->Job->findByid($jid));
        
        if(!empty($this->data))
        {
            $this->Job->id = $jid;
            $this->Job->save($this->data);
            $this->Session->setFlash('Notes have been added');
            $this->redirect('/jobs/mytasks');
            
        }
        
    }
    function ajaddnote($jid)
    {
        App::import('Model', 'User');
        $usr = new User();
        
        //$this->set('usr', $usr->findByid($this->Auth->user('id')));
        $this->set('task', $this->Job->findByid($jid));
        
        if(!empty($this->data))
        {
            $this->Job->id = $jid;
            $this->Job->save($this->data);
             $this->Session->setFlash('Notes have been added');
            $this->redirect('/jobs/jadminlist');
            
        }
        
    }
    function hoursreport()
    {
       //$this->layout = 'low';
       //$this->User->recursive=-1;
         //$options['joins'] = array(
//                    array('table' => 'jobs_users',
//                        'alias' => 'JobsUser',
//                        'type' => 'inner',
//                        'conditions' => array(
//                            'Job.id = JobsUser.job_id'
//                                            )
//                    ),
//                    array('table' => 'users',
//                        'alias' => 'User',
//                        'type' => 'inner',
//                        'conditions' => array(
//                            'JobsUser.user_id = User.id'
//                                            )
//                        )
//            );
//        $options['conditions'] = array(array('Job.sdate <' => date('Y-m-d H:i'), 'User.id' => $this->Auth->user('id')));
//            $this->set('felist', $this->Job->find('all', $options)); 
//            
            
    }
    function hreport($mth, $yr)
    {
        $this->layout = false;
        $str = strtotime($mth . ' ' . $yr);
        $dt = date('Y-m', $str);
        $sumhours = $this->Job->query("Select sum(Job.volhours) FROM jobs as Job WHERE Job.sdate like '". $dt . "%' ");
        
        $options['joins'] = array(
                    array('table' => 'jobs_users',
                        'alias' => 'JobsUser',
                        'type' => 'inner',
                        'conditions' => array(
                            'User.id = JobsUser.user_id'
                                            )
                    ),
                    array('table' => 'jobs',
                        'alias' => 'Job',
                        'type' => 'inner',
                        'conditions' => array(
                            'JobsUser.job_id = Job.id'
                                            )
                        )
            );
        $options['conditions'] = array('Job.sdate LIKE' => $dt.'%', 'Job.volhours >' => '0');
        //$options['fields'] = array('User.id', 'Job.id', 'Job.title');
        $options['group'] = array('User.id');
       // echo pr($options['conditions']);
       
        $this->set('hbyusr', $this->Job->User->find('all', $options));//, array('conditions' => array('Job.sdate LIKE' => $dt .'%'))));
        //$this->set('hbyusr', $this->Job->find('all', $options)); 
        //$this->set('hbyusr',$hbyusr);
        $this->set('sumhours', $sumhours);
        $this->set('range', $dt);
    }
    
}
?>